package com.dingreading.cloud.admin.service.impl;

import com.dingreading.cloud.admin.entity.SubjectLessonApply;
import com.dingreading.cloud.admin.entity.table.SubjectLessonApplyTableDef;
import com.dingreading.cloud.admin.mapper.SubjectLessonApplyMapper;
import com.dingreading.cloud.admin.service.SubjectLessonApplyService;
import com.dingreading.cloud.common.util.NepUtil;
import com.dingreading.cloud.common.util.PageUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryMethods;
import com.mybatisflex.core.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 服务层实现。
 *
 * @author Administrator
 * @since 2024-02-26
 */
@Service
public class SubjectLessonApplyServiceImpl extends BaseServiceImpl<SubjectLessonApplyMapper, SubjectLessonApply, SubjectLessonApplyTableDef> implements SubjectLessonApplyService {

    @Override
    protected SubjectLessonApplyTableDef getTable() {
        return SubjectLessonApplyTableDef.subjectLessonApply;
    }

    @Override
    public Page<SubjectLessonApply> pageList(PageUtil pageUtil, String keywords, Long lessonId, Integer status) {
        QueryCondition condition = QueryCondition.createEmpty();
        if (StringUtils.isNotBlank(keywords))
            condition.and(table.lessonName.like(keywords)
                    .or(table.levelName.like(keywords)));
        if (lessonId != null)
            condition.and(table.lessonId.eq(lessonId));
        if (status != null)
            condition.and(table.status.eq(status));

        QueryWrapper wrapper = QueryWrapper.create()
                .where(condition)
                .orderBy(table.id.desc());

        return getMapper().paginate(Page.of(pageUtil.getPage(), pageUtil.getRows()), wrapper);
    }

    @Override
    public int dropBean(Long id) {
        QueryCondition condition = QueryCondition.createEmpty();
        condition.and(table.id.eq(id))
                .and(table.status.in(0, -1));

        return getMapper().deleteByCondition(condition);
    }

    @Override
    public boolean haveLessonId(Long lessonId) {
        QueryCondition condition = QueryCondition.createEmpty();
        condition.and(table.lessonId.eq(lessonId))
                .and(table.status.eq(0));
        return exists(condition);
    }

    @Override
    public long getMaxId(Long lessonId) {
        QueryWrapper wrapper = QueryWrapper.create()
                .select(QueryMethods.max(table.id))
                .from(table)
                .where(table.lessonId.eq(lessonId));

        Long aLong = getMapper().selectObjectByQueryAs(wrapper, Long.class);
        return NepUtil.nullToZero(aLong);
    }
}
